package com.mall.shopping.services;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dal.persistence.ItemCatMapper;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.Redisson;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * @author ACG
 * @date 2020-11-16 20:30
 */
@Service(interfaceClass = ICartService.class)
@Component
public class ICartServiceImpl implements ICartService {

    @Autowired
    RedissonClient redissonClient;
    @Autowired
    ItemMapper itemMapper;

    //jackson中的对象，来完成json字符串到bean之间的相互转换
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse cartListByIdResponse = new CartListByIdResponse();
        ObjectMapper mapper = new ObjectMapper();
        Long userId = request.getUserId();
        String idString = "user_id_"+userId.toString();
        RedissonClient redisson = Redisson.create();
        //通过userID创建一个RMap对象（具体我也不清楚），猜测是创建一个hset对象,long对应cartID，后者对应具体参数
        RMap<String, CartProductDto> map = redisson.getMap(idString);
        //获取
        List<CartProductDto> cartProductDtoList = new ArrayList<>();
        CartProductDto cartProductDto = new CartProductDto();
        Set<String> set = map.readAllKeySet();
        for (Iterator iter = set.iterator(); iter.hasNext(); ) {
            String temp = (String) iter.next();
            //重复添加
            cartProductDto = map.get(temp);
            cartProductDtoList.add(cartProductDto);
        }
        cartListByIdResponse.setCartProductDtos(cartProductDtoList);
        cartListByIdResponse.setCode("200");
        cartListByIdResponse.setMsg("success");
        return cartListByIdResponse;
    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse addCartResponse = new AddCartResponse();
        Long userId = request.getUserId();
        String idString = "user_id_"+userId.toString();
        Long itemId = request.getItemId();
        Integer num = request.getNum();
        RedissonClient redisson = Redisson.create();
        RMap<String, CartProductDto> map = redisson.getMap(idString);
        CartProductDto cartProductDto = new CartProductDto();
        //判断有无库存
        int selectItemNumForAddCartsById = itemMapper.selectItemNumForAddCartsById(itemId);
        if(selectItemNumForAddCartsById<=0){
            addCartResponse.setCode(ShoppingRetCode.REQUISITE_PARAMETER_NOT_EXIST.getCode());
            addCartResponse.setMsg("该商品已没有库存！");
            return addCartResponse;
        }
        //判断是否存在
        if (map.containsKey(itemId)) {
            //如果存在则数量+num
            cartProductDto = map.get(itemId);
            cartProductDto.setProductNum(cartProductDto.getProductNum()+num);
            map.put("item_id_"+itemId,cartProductDto);
        } else {
            //否则添加一个物品
            cartProductDto=itemMapper.selectItemForAddCartsById(itemId);
            cartProductDto.setChecked("false");
            cartProductDto.setProductNum((long)1);
            map.put("item_id_"+itemId,cartProductDto);
        }
        addCartResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
        addCartResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return addCartResponse;
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        return null;
    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        return null;
    }

    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        return null;
    }


    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        //ctrl+alt+v
        RMap<Object, Object> map = redissonClient.getMap(String.valueOf(request.getUserId()));

        Collection<Object> items = map.readAllValues();
        for (Object item : items) {
            String item1 = (String) item;
            CartProductDto cartProductDto = null;
            try {
                cartProductDto = objectMapper.readValue(item1, CartProductDto.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //拿到checked看是否满足删除的条件
            String checked = cartProductDto.getChecked();
            if ("true".equals(checked)){
                //删除商品
                Long productId = cartProductDto.getProductId();
                map.remove(productId);
            }
        }
        return null;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        return null;
    }
}
